<?php

namespace app\api\controller;


use addons\exam\enum\ExamMode;
use addons\exam\library\ExamService;
use addons\exam\model\UserModel;
use app\admin\model\exam\GradeModel;
use app\admin\model\exam\PaperModel;
use app\common\controller\Api;
use think\Request;

/**
 * 试卷接口
 */
class Paper extends Api
{
    protected $noNeedRight = ['*'];

    //获取试卷id
    public function getPaper()
    {
        $paper = PaperModel::get(['is_show'=>1]);

        $this->success('', $paper->id);
    }

    /**
     * 试卷取题接口
     */
    public function getExamQuestion()
    {
        $paper_id = input('paper_id/d', 0);


        // 获取试卷题目
        $question_data = ExamService::getExamQuestion($paper_id);

        $this->success('', array_merge($question_data));
    }

    /**
     * 交卷
     */
    public function submit()
    {
        $request       = Request::instance();
        $user_id       = $this->auth->id;
        $paper_id      = $request->post('paper_id/d', 0);
        $questions     = $request->post('questions');
        $start_time    = $request->post('start_time/d', time());

        if (!$user_id || !$paper_id || !$questions) {
            $this->error('提交数据有误' . $user_id);
        }
        $questions = _json_decode($questions);
        //dump($questions);die;
        $result = ExamService::paperExam($user_id, $paper_id, $questions, $start_time, $paper);

        // 记录考试成绩
        GradeModel::create(array_merge(
            $result,
            [
                'cate_id'  => $paper['cate_id'],
                'user_id'  => $user_id,
                'paper_id' => $paper_id,
            ],
            [
                // 'exam_mode' => ExamMode::PAPER,
                'date' => date('Y-m-d'),
            ]), true);

        if ($result['is_pass']){
            $user = \app\common\model\User::get($this->auth->id);
            if ($user->is_buy==1){
                $user->level = 2;
            }
            $user->question_pass = 1;
            $user->save();
            //$data = ['question_pass'=>1];

            //\app\admin\model\User::update($data,['id'=>$this->auth->id]);

        }
        $this->success('', $result);

    }

}